"""
The MIT License (MIT)
Copyright © 2020 Walkline Wang (https://walkline.wang)
https://gitee.com/walkline/MicroPython-with-Aligenie-Voice-Skill
"""
import gc
import ntptime
from utime import sleep_ms
from machine import Pin, Timer
from config import Config
from utils.wifihandler import WifiHandler


def hard_reset():
	from machine import reset
	reset()

def blink():
	led = Pin(2, Pin.OUT, value=0)

	for count in range(20):
		led.value(not led.value())
		sleep_ms(200)

def sync_ntp():
	ntptime.NTP_DELTA = 3155644800
	ntptime.host = "ntp1.aliyun.com"
	ntptime.settime()

def connect_to_wifi():
	WifiHandler.set_ap_status(False)
	sleep_ms(1000)

	result_code = WifiHandler.set_sta_mode(Config.WIFI_SSID, Config.WIFI_PASSWORD)

	return result_code

def check_internet_cb(timer):
	if not WifiHandler.get_sta_status() or not WifiHandler.check_internet_connection():
		print("Wifi disconnected or lost internet connection, restarting now...")

		hard_reset()
	
	gc.collect()


if __name__ == "__main__":
	if WifiHandler.STATION_CONNECTED == connect_to_wifi():
		if WifiHandler.check_internet_connection():
			sync_ntp()
			Pin(2, Pin.OUT, value=1)

			check_internet_timer = Timer(1)
			check_internet_timer.init(
				mode=Timer.PERIODIC,
				period=(Config.MQTT_KEEPALIVE - 5) * 1000,
				callback=check_internet_cb
			)

			print("Timer started, periodic {} seconds".format(Config.MQTT_KEEPALIVE))

			gc.collect()
		else:
			print("Connected to wifi, but no internet connection, restarting now...")

			blink()
			sleep_ms(1000)
			hard_reset()			
	else:
		print("Cannot connect to specified wifi, restarting now...")

		blink()
		sleep_ms(1000)
		hard_reset()
